package deibay.server.network.socket;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.messages.Message;
import deibay.util.ParserXML;

public class UDPService {

	public UDPService() {
		try {
			udpSocket = new DatagramSocket();			
			multicastSocket = new MulticastSocket(MULTICAST_PORT);
			InetAddress group = InetAddress.getByName(GROUP_IP);
			multicastSocket.joinGroup(group);					
		} catch (UnknownHostException e) {		
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao criar udp.\n");
		} catch (IOException e) {			
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao criar udp.\n");
		}
	}


	public void sendMessage(Message message){
		try {
			ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024);	       
			os = new DataOutputStream(new BufferedOutputStream(byteStream));

			os.flush(); 
			os.writeUTF(ParserXML.getInstance().parseMessageToXML(message)); 
			os.flush(); 

			byte[] sendBuf = byteStream.toByteArray(); 
			DatagramPacket packet = new DatagramPacket(sendBuf, sendBuf.length, InetAddress.getByName(GROUP_IP), MULTICAST_PORT); 

			DeibayLogger.getInstance().getLog().log(Level.WARNING, "UDP: A enviar " + message.toString()+".\n");

			udpSocket.send(packet); 
			os.close(); 
		} catch (IOException e) {			
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao enviar mensagem de publicidade.\n");
		} 
	}		

	public void run() {		
	}

	public void close()
	{			
		try {
			keepAlive = false;
			udpSocket.close();
			os.close();
			is.close();				
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}

	private DatagramSocket udpSocket;	
	private MulticastSocket multicastSocket;
	private boolean keepAlive = true;
	private DataOutputStream os = null;
	private DataInputStream is = null;

	private final int MULTICAST_PORT = 32001;
	private final String GROUP_IP = "228.5.6.7";
}
